/*
 * Created on 21-ago-2004
 *
 */
package guru.util;


import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sun.mail.smtp.SMTPMessage;
import com.sun.mail.smtp.SMTPTransport;

/**
 * @author cobach
 *
 */
public class EMailer {
    

    public static void sendmail(String from, String to, String subject, String message){
        Properties props = new Properties();
        props.put("mail.smtp.host","localhost");   

        try{

           Session session = Session.getDefaultInstance(props, null);
            //session.setDebug(debug);

            // create a message
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));

            InternetAddress[] address = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
                msg.setSentDate(new Date());
            // If the desired charset is known, you can use
                // setText(text, charset)
            msg.setText(message);
                Transport.send(msg);
        }
        catch (Exception e) {
            System.err.println("Ha colocado una direccion invalida");
            System.err.println(""+e);
        }
    }

    private static void sendmail(String from, String to, String subject, String mensaje, boolean myhost) throws Exception {
        Properties prop = new Properties();
        String server = "mail.cantv.net";
        prop.put("mail.smtp.host", server);
        prop.put("mail.smtp.sendpartial", "true");
        Session sess = Session.getDefaultInstance(prop, null);
        
        MimeMessage message = new MimeMessage(sess);	      
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = {new InternetAddress(to)};
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(mensaje);            
        URLName myURL = new URLName("SMTP",server,-1,"","","");
        SMTPTransport myTra = new SMTPTransport(sess, myURL);
        
        SMTPMessage smtpMsg = new SMTPMessage((MimeMessage) message);
        System.out.println(smtpMsg.getRecipients(Message.RecipientType.TO).toString());
        try {  
            myTra.connect();
            myTra.sendMessage(smtpMsg, smtpMsg.getRecipients(Message.RecipientType.TO));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
